<?php

namespace App\Exports;

use App\Models\Order;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithCustomValueBinder;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Cell\DataType;

class InvoiceExport extends BaseExport implements WithCustomValueBinder, FromQuery
{
    private $commodityActivities;

    private $attributes = [];

    public function __construct($commodityActivities, \Illuminate\Http\Request $request = null)
    {
        parent::__construct($request);

        $this->commodityActivities = $commodityActivities;

        activity()
            ->on($this->commodityActivities)
            ->by(\Auth::user())
            ->withProperty('ip', app('request')->ip())
            ->log(sprintf('导出 %s (%s) 发货单', $this->commodityActivities['name'] ?? '', $this->commodityActivities['numbering'] ?? ''));
    }

    public function headings(): array
    {
        $this->commodityActivities->attributes->each(fn($attribute) => $this->attributes[] = [
            'id' => $attribute['id'],
            'name' => $attribute['name']
        ]);

        return [
            '订单编号',
            '商品名称',
            'SKU以及数量',
            'SKU总数',
            '收货人',
            '收货人手机号',
            '地址',
            '备注',
            '管理员备注',
        ];
    }

    public function map($row): array
    {
        $skuList = [];
        $amount = 0;
        foreach ($row['skus'] as $sku) {
            $values = arrayCombineByKey($sku['sku_snapshot']['values'], 'attribute_id'); // 规格值
            $skuList[] = implode(';', array_map(static fn($attribute) => $values[$attribute['id']]['content'], $this->attributes)) . ' * ' . $sku['amount'];

            $amount += $sku['amount'];
        }

        return [
            $row['numbering'] ?? '',
            $this->commodityActivities->commodity['name'] ?? '',
            implode(' ', $skuList),
            $amount,
            iconv('GBK', 'UTF-8', iconv('UTF-8', 'GBK//IGNORE', $this->removeEmoji($row['client_name'] ?? ''))),
            $row['client_phone'] ?? '',
            $this->removeUncommonWords($this->removeEmoji($row['client_address'] ?? '')),
            $this->removeUncommonWords($this->removeEmoji($row['remark'] ?? '')),
            $row['management_notes'] ?? '',
        ];
    }

    /**
     * @return \App\Models\Base|Order|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder
     */
    public function query()
    {
        return Order::query()
            ->with(['agent', 'skus'])
            ->where('commodity_activity_id', $this->commodityActivities['id'])
            ->where('status', Order::STATUS_TO_BE_DELIVERED);
    }

    public function bindValue(Cell $cell, $value)
    {
        if (is_numeric($value)) {
            $cell->setValueExplicit($value, DataType::TYPE_STRING);

            return true;
        }

        // else return default behavior
        return parent::bindValue($cell, $value);
    }
}
